package com.tuyan.aixiang.activity.fullplayer;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gyf.immersionbar.ImmersionBar;
import com.tuyan.aixiang.R;
import com.tuyan.aixiang.activity.web.WebActivity;
import com.tuyan.aixiang.common.BaseActivity;
import com.tuyan.aixiang.common.Constant;
import com.tuyan.aixiang.common.StorageKey;
import com.tuyan.aixiang.component.DeviceControl;
import com.tuyan.aixiang.component.EZUIPlayerView;
import com.tuyan.aixiang.component.PTZBtn;
import com.tuyan.aixiang.component.VidControl;
import com.tuyan.aixiang.component.VoiceBtn;
import com.tuyan.aixiang.model.YsDevice;
import com.tuyan.aixiang.util.EZOpenUtils;
import com.tuyan.aixiang.util.Log;
import com.tuyan.aixiang.util.StorageUtil;
import com.tuyan.aixiang.util.ToastUtil;
import com.videogo.exception.BaseException;
import com.videogo.openapi.EZPlayer;
import com.videogo.openapi.EZTalk;
import com.videogo.openapi.OnEZPlayerCallBack;
import com.videogo.openapi.OnEZTalkCallBack;

import java.util.concurrent.atomic.AtomicBoolean;

import butterknife.BindView;
import butterknife.OnClick;

import static android.view.View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;

public class FullPlayerActivity extends BaseActivity<FullPlayerPresenter> implements FullPlayer.View {

    private static final String TAG = "FullPlayerActivity";


    public final static int STATUS_INIT = 1;
    public final static int STATUS_START = 2;
    public final static int STATUS_PLAY = 3;
    public final static int STATUS_STOP = 4;


    private YsDevice curDevice;

    private boolean needValidate = true;

    private EZPlayer mPlayer;

    private EZTalk mTalk;

    @BindView(R.id.epv_player)
    EZUIPlayerView epvPlayer;

    @BindView(R.id.vb_voice)
    VoiceBtn vbVoice;

    @BindView(R.id.pb_ptz)
    PTZBtn pbPtzBtn;

    @BindView(R.id.pb_full_ptz)
    PTZBtn pbFullPtzBtn;

    @BindView(R.id.tv_title)
    TextView tvTitle;

    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;

    @BindView(R.id.vc_control)
    VidControl vcControl;

    @BindView(R.id.dc_control)
    DeviceControl dcControl;


    /**
     * 播放器状态
     */
    public int mStatus = STATUS_INIT;


    /**
     * resume时是否恢复播放
     */
    private AtomicBoolean isResumePlay = new AtomicBoolean(true);

    /**
     * surface是否创建好
     */
    private AtomicBoolean isInitSurface = new AtomicBoolean(false);

    private boolean isSoundOpen = true;

    private boolean mIsOnTalk = false;

    /**
     * 打开Activity
     *
     * @param device YsDevice
     */
    public static void startPlayActivity(Context context, YsDevice device) {
        Intent intent = new Intent(context, FullPlayerActivity.class);
        intent.putExtra("device", device);
        context.startActivity(intent);
    }


    @Override
    public void bindView() {
        super.bindView();
        Intent intent = getIntent();
        curDevice = (YsDevice) intent.getSerializableExtra("device");
//        if (BuildConfig.DEBUG) {
//            curDevice.setChannelNo(1);
//            curDevice.setEncrypted(0);
//        }

        needValidate = curDevice.getEncrypted().equals(1);
        // set title
        tvTitle.setText(curDevice.getDeviceName());
        vcControl.setTitle(curDevice.getDeviceName());

        iPresenter.init(curDevice);

    }

    @Override
    public void unBindView() {
        if (null != mPlayer) {
            mPlayer.release();
        }

        super.unBindView();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mStatus != STATUS_STOP) {
            isResumePlay.set(true);
        }
        stopRealPlay();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isResumePlay.get() && isInitSurface.get()) {
            isResumePlay.set(false);
            startRealPlay();
        }
        if (StorageUtil.getBoolean(StorageKey.CLOSE_BACK, false)) {
            StorageUtil.setBoolean(StorageKey.CLOSE_BACK, false);
            finish();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_full_player;
    }

    @Override
    protected FullPlayerPresenter createPresenter() {
        return new FullPlayerPresenter();
    }

    @Override
    public void toggleFullscreen(boolean full) {
        View decorView = getWindow().getDecorView();
        if (full) {
            rlTitle.setVisibility(View.GONE);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //隐藏状态栏
            ImmersionBar.with(this).fitsSystemWindows(false).statusBarColor("#00000000").fullScreen(true).init();

            int option = SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            decorView.setSystemUiVisibility(option);

        } else {
            rlTitle.setVisibility(View.VISIBLE);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //显示状态栏
            ImmersionBar.with(this).keyboardEnable(true)  //解决软键盘与底部输入框冲突问题
//                .flymeOSStatusBarFontColor(R.color.textDark)
                    .statusBarDarkFont(true, 0.2f)
                    .fitsSystemWindows(true)
                    .statusBarColor("#ffffff")
                    .init();
        }
        setSurfaceSize();
    }

    @Override
    public void initPlayer() {
        epvPlayer.setSurfaceHolderCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                if (null != mPlayer) {
                    mPlayer.setSurfaceHold(holder);
                }
                Log.d(TAG, "surfaceCreated isInitSurface = " + isInitSurface);
                if (isInitSurface.compareAndSet(false, true) && isResumePlay.get()) {
                    isResumePlay.set(false);
                    startRealPlay();
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                isInitSurface.set(false);
            }
        });


        // 创建视频及语音实例
        mPlayer = EZPlayer.createPlayer(curDevice.getDeviceSerial(), curDevice.getChannelNo());
        mTalk = EZTalk.createEZTalk(curDevice.getDeviceSerial(), curDevice.getChannelNo());

        mPlayer.setOnEZPlayerCallBack(new OnEZPlayerCallBack() {
            @Override
            public void onPlaySuccess() {
                Log.d(TAG, "PlaySuccess");
                if (mStatus != STATUS_STOP) {
                    handlePlaySuccess();
                }
            }

            @Override
            public void onPlayFailed(BaseException e) {
                Log.d(TAG, "PlayFailed");
                e.printStackTrace();
                handlePlayFail(e);
            }

            @Override
            public void onVideoSizeChange(int i, int i1) {
                Log.d(TAG, "PlayVideoSizeChange");

            }

            @Override
            public void onCompletion() {
                Log.d(TAG, "PlayCompletion");

            }
        });

        mTalk.setOnEZTalkCallBack(new OnEZTalkCallBack() {
            @Override
            public void onTalkSuccess() {
                Log.d(TAG, "onTalkSuccess");
            }

            @Override
            public void onTalkFailed(BaseException e) {
                Log.d(TAG, "onTalkFailed");
            }

            @Override
            public void onTalkStoped() {
                Log.d(TAG, "onTalkStoped");

            }
        });

        if (needValidate) {
            mPlayer.setPlayVerifyCode(curDevice.getValidateCode());
        }
//        mPlayer.startRealPlay();


        vcControl.setup(new VidControl.ControlAction() {
            @Override
            public void onTogglePlay(boolean play) {
                if (play) {
                    startRealPlay();
                } else {
                    stopRealPlay();
                }
            }

            @Override
            public void onToggleVoice(boolean mute) {
                isSoundOpen = !mute;
                setRealPlaySound();
            }

            @Override
            public void onToggleFullscreen(boolean full) {
                vcControl.syncPtz(false);
                vcControl.syncTalk(false);
//                vcControl.syncVoice(false);
                pbFullPtzBtn.setVisibility(View.GONE);
                stopVoiceTalk();
                toggleFullscreen(full);

                // 全屏打开对讲
                if(full) {
                    prepareVoiceTalk();
                } else {
                    finishVoiceTalk();
                }
            }

            @Override
            public void onRefresh() {
                reStartPlay();
            }

            @Override
            public void onToggleResolution(boolean hd) {
                toggleResolution(hd);
            }

            @Override
            public void onTogglePtz(boolean on) {
                if (on) {
                    showFullPTZ();
                } else {
                    pbFullPtzBtn.setVisibility(View.GONE);
                }
            }

            @Override
            public void onToggleTalk(boolean on) {
                if (!supportTalk) {
                    ToastUtil.makeShort("设备不支持对讲");
                    return;
                }
                if (on) {
                    startVoiceTalk();
                } else {
                    stopVoiceTalk();
                }
            }
        });

        dcControl.setOnMicClick(v -> showVoice()); // prepareVoiceTalk
        dcControl.setOnPTZClick(v -> showPTZ());

        vbVoice.setListener(() -> withRecordPermission(this::startVoiceTalk), this::stopVoiceTalk, this::finishVoiceTalk);
    }

    @Override
    public void showPTZ() {
        if (this.supportPtz) {
            pbPtzBtn.setVisibility(View.VISIBLE);
        } else {
            ToastUtil.makeLong("设备不支持云台控制");
        }
    }

    @Override
    public void showFullPTZ() {
        if (this.supportPtz) {
            pbFullPtzBtn.setVisibility(View.VISIBLE);
        } else {
            vcControl.syncPtz(false);
            ToastUtil.makeLong("设备不支持云台控制");
        }
    }


    @Override
    public void showVoice() {
        if (supportTalk) {
            vbVoice.setVisibility(View.VISIBLE);
            // 开启对讲
            prepareVoiceTalk();
        } else {
            ToastUtil.makeLong("设备不支持对讲");
        }
    }

    @Override
    public void setQuilityResult(boolean hd) {
        vcControl.syncResolution(hd);
    }

    private boolean supportTalk = false;

    private boolean supportPtz = false;

    @Override
    public void setPTZEnable(boolean support) {
        supportPtz = support;
        pbPtzBtn.setup(curDevice, false);
        pbFullPtzBtn.setup(curDevice, true);
        pbFullPtzBtn.setOnClose(() -> vcControl.syncPtz(false));
//        showPTZ();
    }

    @Override
    public void setTalkModeEnable(boolean support) {
        supportTalk = support;
//        showVoice();
    }

    @OnClick(R.id.iv_back)
    public void back() {
        finish();
    }

    @OnClick(R.id.iv_setting)
    public void setting() {
        Intent inte = new Intent(this, WebActivity.class);
        String link = Constant.CAMERA_SETTING + "?id=" + curDevice.getId();
        inte.putExtra("url", link);
        startActivity(inte);
    }

    private void realStartPlay(String mVerifyCode) {
        if (!TextUtils.isEmpty(mVerifyCode)) {
            mPlayer.setPlayVerifyCode(mVerifyCode);
        }
        mStatus = STATUS_START;
        startRealPlayUI();
        mPlayer.startRealPlay();
    }

    /**
     * 开始播放
     */
    private void startRealPlay() {
        Log.d(TAG, "startRealPlay  mStatus = " + mStatus);
        if (mStatus == STATUS_START || mStatus == STATUS_PLAY) {
            return;
        }
        //检测网络
        if (!EZOpenUtils.isNetworkAvailable(this)) {
            return;
        }
        //设备信息为空
        if (null == curDevice) return;
//        if (mPlayPresenter.getOpenDeviceInfo() == null || mPlayPresenter.getOpenCameraInfo() == null) {
//            return;
//        }
        if (!needValidate) {
            realStartPlay(null);
        } else {
            realStartPlay(curDevice.getValidateCode());
        }
        refreshPlayStutsUI();
    }


    /**
     * 停止播放
     */
    private void stopRealPlay() {
        stopRealPlayUI();
        if (mPlayer != null) {
            mPlayer.stopRealPlay();
        }
        refreshPlayStutsUI();
    }

    private void startRealPlayUI() {
        epvPlayer.showLoading();
    }

    private void stopRealPlayUI() {

        mStatus = STATUS_STOP;
        refreshPlayStutsUI();
    }


    /**
     * 重启播放
     */
    private void reStartPlay() {
        if (mStatus == STATUS_PLAY) {
            // 停止播放
            stopRealPlay();
            //下面语句防止stopRealPlay线程还没释放surface, startRealPlay线程已经开始使用surface
            //因此需要等待500ms
            SystemClock.sleep(500);
            // 开始播放
            startRealPlay();
        }
    }

    private void refreshPlayStutsUI() {
        switch (mStatus) {
            case STATUS_PLAY:
                epvPlayer.dismissomLoading();
                vcControl.syncPlay(true);
                break;
            case STATUS_STOP:
                epvPlayer.dismissomLoading();
                vcControl.syncPlay(false);
                break;
            default:
                break;
        }
    }

    /**
     * 处理播放成功的情况
     */
    private void handlePlaySuccess() {
        mStatus = STATUS_PLAY;
        refreshPlayStutsUI();
        // 声音处理
        setRealPlaySound();
        // TODO is support talk
//        if (mPlayPresenter.getOpenDeviceInfo() != null && mPlayPresenter.getOpenDeviceInfo().supportTalkMode() != 0) {
//            mPlayUI.mTalkImg.setEnabled(true);
//        } else {
//            mPlayUI.mTalkImg.setEnabled(false);
//        }
//        mHandler.sendEmptyMessage(MSG_REFRESH_PLAY_UI);
    }


    /**
     * 设置播放是否开启音频
     */
    private void setRealPlaySound() {
        if (mPlayer != null) {
            if (isSoundOpen) {
                mPlayer.openSound();
            } else {
                mPlayer.closeSound();
            }
        }
    }

    /**
     * 处理播放失败的情况
     */
    private void handlePlayFail(BaseException e) {
        if (mStatus != STATUS_STOP) {
            mStatus = STATUS_STOP;
            epvPlayer.dismissomLoading();
            stopRealPlay();
            // TODO play failed
            ToastUtil.makeLong("视频播放失败" + e.getErrorCode());
//            updateRealPlayFailUI(e.getErrorCode());
        }
    }

    private void toggleResolution(boolean hd) {
        if (null != mPlayer && mStatus != STATUS_STOP) {
            iPresenter.setQuality(hd);
        }
    }

    /**
     * 按下开始设备对讲
     */
    private void startVoiceTalk() {
        Log.d(TAG, "startVoiceTalk");
        if (mPlayer == null) {
            Log.d(TAG, "EZPlaer is null");
            return;
        }
        mTalk.setVoiceTalkStatus(true);
    }

    /**
     * 松开手指停止对讲
     */
    private void stopVoiceTalk() {
        if (!iPresenter.isValidDevice() || mPlayer == null) {
            return;
        }
        Log.d(TAG, "stopVoiceTalk");
        mTalk.setVoiceTalkStatus(false);
    }

    /**
     * 开启talk
     */
    private void prepareVoiceTalk() {
        Log.d(TAG, "startVoiceTalk");
        if (mPlayer == null) {
            Log.d(TAG, "EZPlaer is null");
            return;
        }
        mIsOnTalk = true;
        if (isSoundOpen) {
            mPlayer.closeSound();
        }
        mTalk.startVoiceTalk();
    }

    /**
     * 完成talk
     */
    private void finishVoiceTalk() {
        if (!iPresenter.isValidDevice() || mPlayer == null) {
            return;
        }
        Log.d(TAG, "stopVoiceTalk");
        mTalk.stopVoiceTalk();
        mTalk.setVoiceTalkStatus(false);
        handleVoiceTalkStoped();
    }


    private void handleVoiceTalkStoped() {
        if (mIsOnTalk) {
            mIsOnTalk = false;
        }
        if (mStatus == STATUS_PLAY) {
            if (mPlayer != null) {
                setRealPlaySound();
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (vcControl.isFullscreen()) {
                vcControl.triggerFullscreen(false);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    protected void setSurfaceSize() {
        Log.i(TAG, "setSurfaceSize");
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        if (vcControl.isFullscreen()) {
            pbFullPtzBtn.setVisibility(View.GONE);
            epvPlayer.setSurfaceSize(0, dm.heightPixels);
        } else {
            epvPlayer.setSurfaceSize(dm.heightPixels, 0);
        }
    }
}
